import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

public class WordTemplateFiller2 {
    public static void main(String[] args) {

        // 创建数据映射
        Map<String, String> data = new HashMap<>();
        data.put("P1", "1");
        data.put("P2", "2");
        data.put("P3", "3");
        data.put("P4", "4");
        data.put("P5", "5");
        data.put("P6", "6");
        data.put("P7", "7");
        data.put("P8", "8");
        data.put("P9", "9");
        data.put("P10", "10");
        data.put("P11", "11");
        data.put("P12", "12");
        data.put("P13", "13");
        data.put("P14", "14");
        data.put("P15", "15");
        data.put("P16", "16");
        data.put("P17", "17");
        data.put("P18", "18");
        data.put("T1", "20");
        data.put("T2", "21");
        data.put("T3", "22");
        data.put("T4", "23");
        data.put("T5", "24");
        data.put("T6", "25");
        data.put("T7", "26");
        data.put("T8", "27");


        //构建月报
        buildMonthWord(data,"temp.docx","output2.docx");
    }

    /**
     * 构建
     */
    public static void buildMonthWord(Map<String, String> data,String templatePath, String outputPath) {
        try (FileInputStream fis = new FileInputStream(templatePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            WordUtils.insertStyledParagraph(document, 11, "共同生活家庭成员一，姓名_ 张三 _，性别_ 男 _，年龄_ 45 _周岁，与户主关系_ 户主 _，与户主赡（抚、扶）养关系是_ 无 _关系，教育程度_ 高中 _，职业_ 企业经理 _，县级及以上医院确诊患病医学病种名称_ 无 _，残疾类型_ 听力残疾 _，残疾等级_ 三级残疾 _，经_ 民政 _部门认定生活自理能力_ 无 _。", 2);
            WordUtils.insertStyledParagraph(document, 12, "（3）共同生活家庭成员二,与户主户籍关系：_户主_，教育程度：_小学未毕业_", 2);
            WordUtils.replaceKeywordWithImage(document,"image","D:\\Temp\\image.png",100,100);
            WordUtils.replaceTableKeywords(document, data);
            // 保存文档
            try (FileOutputStream fos = new FileOutputStream(outputPath)) {
                document.write(fos);
            }

            System.out.println("新内容已添加，文档保存成功！");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 设置单元格内容的方法
    public static void setCellText(XWPFTableCell cell, String text, int fontSize, String fontFamily, ParagraphAlignment alignment) {
        // 清空单元格内容
        cell.removeParagraph(0);
        // 设置新的段落和文本
        XWPFParagraph paragraph = cell.addParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText(text);
        // 设置字体大小
        run.setFontSize(fontSize);
        // 设置字体
        run.setFontFamily(fontFamily);
        // 设置段落对齐方式
        paragraph.setAlignment(alignment);
    }
}
